﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;

namespace TextPioneer.Facade
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		protected override void OnStartup(StartupEventArgs e)
		{
			base.OnStartup(e);
			try
			{
				IDataProvider dataProvider = null;
				if (e.Args.Length == 1)
				{
					dataProvider = LoadDataSet(e.Args[0]);
				}
				else
				{
					Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
					openDlg.Filter = "Dataset Definitions|*.dbdef|All Files|*.*";
					openDlg.DefaultExt = "dbdef";
					var result = openDlg.ShowDialog();
					if (!result.HasValue)
					{
						return;
					}
					if (result.GetValueOrDefault())
					{
						dataProvider = LoadDataSet(openDlg.FileName);
					}
				}
				if (dataProvider != null)
				{
					using (dataProvider)
						new MainWindow(dataProvider).ShowDialog();
				}
			}
			finally
			{
				Shutdown();
			}
		}

		private IDataProvider LoadDataSet(string fileName)
		{
			try
			{
				var def = DataDefinition.Parse(File.ReadAllText(fileName));
				var curDir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
				var providerDllPath = Path.Combine(curDir, string.Format("providers\\{0}.dll", def.DataProviderName));
				Assembly asm = Assembly.LoadFile(providerDllPath);
				var providerType = asm.GetTypes().Where(t => t.IsClass && t.GetInterface(typeof(IDataProvider).Name) != null).FirstOrDefault();
				if (providerType == null)
				{
					throw new Exception("The specified DataProvider does not implement IDataProvider.");
				}
				var provider = Activator.CreateInstance(providerType) as IDataProvider;
				provider.Initialize(Path.Combine(Path.GetDirectoryName(fileName), def.DataSource));
				return provider;
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
			}
			return null;
		}
	}
}
